package com.yuanian.ecsplus.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yuanian.dp.common.vo.CustomeFieldValueVo;
import com.yuanian.ecsplus.platform.PlatformSupport;
import com.yuanian.ecsplus.platform.SpringContextBean;
import com.yuanian.ecsplus.context.ReflectContext;
import com.yuanian.ecsplus.vo.AttachmentVo;
import com.yuanian.infrastructure.util.service.IDGenerator;
import com.yuanian.infrastructure.util.service.JsonUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import java.util.List;

/**
 * 附件结果的处理
 */
public class AttachmentResultHandler implements ResultHandler {

    @Override
    public void obj2Map(ReflectContext reflectContext) {
        reflectContext.putMapData(attachmentHandle(reflectContext.getResult()));
    }

    @Override
    public void map2Obj(ReflectContext reflectContext) {
        reflectContext.setFieldData();
    }

    private String attachmentHandle(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof String) {
            return getAttachmentJson((String) obj);
        } else if (obj instanceof CustomeFieldValueVo) {
            CustomeFieldValueVo CustomeFieldValueVo = (CustomeFieldValueVo)obj;
            return getAttachmentJson((String)CustomeFieldValueVo.getFieldValue());
        }
        return null;
    }

    private String getAttachmentJson(String obj) {
        JSONArray arr = JSONObject.parseArray(obj);
        List<String> fileIds = Lists.newArrayList();
        List<AttachmentVo> attachmentVoList = Lists.newArrayList();
        for (int i = 0; i < arr.size(); i++) {
            JSONObject jsonObject = (JSONObject) arr.get(i);
            AttachmentVo file = jsonObject.toJavaObject(AttachmentVo.class);
            if (StringUtils.isEmpty(file.getUuid())) {
                //新增
                file.setUuid(IDGenerator.newID());
                file.setIsDefault("N");
                file.setSize(file.getFileSize());
                attachmentVoList.add(file);
            } else {
                //删除的场景
                if (file.getIsDelete().equals("Y")) {
                    fileIds.add(file.getObjectId());
                } else {
                    attachmentVoList.add(file);
                }
            }
        }
        // 删除附件
        if (CollectionUtils.isNotEmpty(fileIds)) {
            SpringContextBean.getBean(PlatformSupport.class).batchdeleteFile(fileIds);
        }
        String attachmentJson = JsonUtils.toJSON(attachmentVoList);
        return attachmentJson;
    }

}
